﻿using UnityEngine;
using System.Collections;

public class Asteroid : MonoBehaviour {

	public float hp = 5;
	public float smaller_hp = 4;
	public GameObject die_fx;
	
	public Material hit_flash_material;
	private Material original_material;
	private float hitflash = 0f;
	private SpriteRenderer sprren;
	
	void Start()
	{
		// hitflash
		sprren = gameObject.GetComponent<SpriteRenderer>();
		if(sprren)
			original_material = sprren.material;
		
	}
	void Update()
	{
		if(hit_flash_material!=null)
		{
			if(hitflash>0f)
			{
				hitflash -= Time.deltaTime;
				
				if(hitflash <= 0f)
				{
					sprren.material = original_material;
				}
			}
		}
	}
	void CloneSelf()
	{
		if(smaller_hp>1)
		{
			GameObject clone = Instantiate(gameObject,transform.position,transform.rotation)as GameObject;
			clone.transform.localScale = new Vector3(transform.localScale.x,transform.localScale.y,transform.localScale.z)*0.5f;
			
			clone.GetComponent<Asteroid>().hp = smaller_hp;
			clone.GetComponent<Asteroid>().smaller_hp = smaller_hp-1;
			
			Vector3 r = new Vector3(Random.Range(-100,100),Random.Range(-100,100),0f);
			r.Normalize();
			r *= transform.localScale.x;
			
			clone.rigidbody2D.velocity = r*2;
			
			clone.rigidbody2D.mass = rigidbody2D.mass/2;
			
			clone.transform.position += r/2;
			
			clone.renderer.material = original_material;
		}
	}
	
	void OnCollisionEnter2D(Collision2D c)
	{
		if(c.gameObject.tag == "Bullet")
		{
			Destroy(c.gameObject);
			
			hp-=c.gameObject.GetComponent<Bullet>().damage;
			
			if(hit_flash_material!=null)
			{
				hitflash = 0.05f;
				if(sprren)
					sprren.material = hit_flash_material;
			}
				
			if(hp<=0)
			{
				CloneSelf();
				CloneSelf();
				CloneSelf();
				
				
				GameObject explosion = Instantiate(die_fx,transform.position,transform.rotation)as GameObject;
				Destroy (explosion,explosion.particleSystem.startLifetime);
				Destroy (gameObject);
			}
		}
		
		
	}
}
